﻿/*****************************************************************************/
CREATE PROCEDURE [GrantManagement].[SaveGrantEvent]
@OID			bigint				= NULL,
@Version		rowversion			= NULL,
@GrantID		bigint,
@ActivityID		bigint,
@EventNotes		varchar(max)		= NULL,
@CreatedBy      uniqueidentifier,
@CreatedOn		datetime,
@CompletedBy	uniqueidentifier	= NULL,
@CompletedOn	datetime			= NULL

AS  

DECLARE @RetCode int,
        @RowCount int

-- 1. If new record (OID is not set)
IF ISNULL(@OID, 0) <= 0 
BEGIN
	-- 1.1. Perform insert (OID is identity).
	INSERT INTO dbo.GrantEvents
	(GrantID, ActivityID, EventNotes, CreatedBy, CreatedOn, CompletedBy, CompletedOn)
	VALUES
	(@GrantID, @ActivityID, @EventNotes, @CreatedBy, @CreatedOn, @CompletedBy, @CompletedOn)

	-- 1.2. Determine OID of newly inserted object
	SET @OID = SCOPE_IDENTITY()
END

-- 2. If OID is set (existing record)
ELSE
BEGIN
	-- 2.1. Attempt updating object (using both OID and timestamp for concurrency reasons)
	UPDATE dbo.GrantEvents
	SET GrantID = @GrantID
	    ,ActivityID = @ActivityID
	    ,EventNotes = @EventNotes
	    ,CompletedBy = @CompletedBy
	    ,CompletedOn = @CompletedOn
	WHERE ((OID = @OID) AND (Version = @Version))
    SELECT @RetCode = @@ERROR, @RowCount = @@ROWCOUNT
    IF (@RetCode <> 0) GOTO ExitError

	-- 2.2. If no records were found (and updated) - it means that
	-- another process had updated this record (therefore timestamp will be different)
	-- or record was deleted (OID not found)
	-- Either way, we need to raise exception
	IF @RowCount = 0
	BEGIN
		RAISERROR(99999, 16, 1, 'GrantEvent' ) --WITH LOG
		GOTO ExitError
	END
END 

---------------------------------------------------------------------------------------------------
--	Return the values to the caller
---------------------------------------------------------------------------------------------------
SELECT OID AS 'OID', Version AS 'Version'
FROM dbo.GrantEvents
WHERE OID = @OID

RETURN(0)

ExitError:
	RETURN(1)
